<template>
  <div class="factory-cust-chart factory-chart" :index="grpFlter.index">
    <div class="chart-handler" v-if="editable">
      <template v-if="!wrong && showList">
        <el-button type="primary" size="mini" @click="$emit('handleDeep')">深入分析</el-button>
      </template>
      <el-dropdown>
        <i class="el-icon-more"></i>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item icon="el-icon-edit" @click.native="$emit('editChart')">
            编辑
          </el-dropdown-item>
          <el-dropdown-item icon="el-icon-close" @click.native="$emit('deleteChart')">
            删除
          </el-dropdown-item>
          <template v-if="!wrong">
            <el-dropdown-item @click.native="$emit('export')" class="drop-item">
              <icon-svg name="iconFacExport"></icon-svg>
              导出结果集
            </el-dropdown-item>
            <el-dropdown-item
              icon="el-icon-download"
              @click.native="$emit('downloadChart', { chart: barChart, name: grpFlter.mainGrp.groupName })"
            >
              下载统计图
            </el-dropdown-item>
          </template>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
    <el-row :gutter="50">
      <el-col :span="grpFlter.isCompare ? 12 : 24" v-loading="loading">
        <template v-if="!wrong">
          <div
            class="chart-content"
            :id="`factory-profile-${grpFlter.mainGrp.labId}-#${grpFlter.index}`"
            v-if="showList"
          ></div>
          <div class="chart-content no-record" v-else>
            <div class="chart-title">
              {{ grpFlter.mainGrp.groupName }} <span class="tips">{{ axisTips }}</span>
            </div>
            <img src="~@/assets/img/no_profile.png" /> <br />
            暂无结果
          </div>
        </template>
        <div class="chart-content no-record" v-else>
          <template v-if="!loading">
            <div class="chart-title">
              {{ grpFlter.mainGrp.groupName }} <span class="tips">{{ axisTips }}</span>
            </div>
            <div>
              <img src="~@/assets/img/no_records.png" /> <br />
              计算出错
            </div>
          </template>
        </div>
      </el-col>
      <el-col :span="12" v-if="grpFlter.isCompare" v-loading="compare.loading">
        <template v-if="!compare.wrong">
          <div
            class="chart-content"
            :id="`factory-profile-compare-${grpFlter.mainGrp.labId}-#${grpFlter.index}`"
            v-if="compare.showList"
          ></div>
          <div class="chart-content no-record" v-else>
            <div class="chart-title">
              对比画像
              <span class="tips">{{ axisTips }}</span>
            </div>
            <img src="~@/assets/img/no_profile.png" /> <br />
            暂无结果
          </div>
        </template>
        <div class="chart-content no-record" v-else>
          <template v-if="!compare.loading">
            <div class="chart-title">
              对比画像
              <span class="tips">{{ axisTips }}</span>
            </div>
            <div>
              <img src="~@/assets/img/no_records.png" /> <br />
              计算出错
            </div>
          </template>
        </div>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import * as echarts from 'echarts'
export default {
  props: {
    grpFlter: {
      type: Object,
      required: true,
      default: () => {}
    },
    editable: {
      type: Boolean,
      default: true
    },
    grpTotal: {
      // 客户数
      type: Object,
      default: () => {
        return {
          grpTotal: 0,
          compareTotal: 0
        }
      }
    }
  },
  data() {
    return {
      loading: false,
      barChart: null,
      wrong: false,
      list: [],
      showList: true,
      compare: {
        loading: false,
        barChart: null,
        wrong: false,
        list: [],
        showList: true
      },
      colorList: ['#0f80ff', '#11ce98', '#f79e2a', '#7886c5', '#e8d318', '#4dad30', '#f3b177']
    }
  },
  computed: {
    axisTips() {
      const tips1 =
        this.grpFlter.mainGrp.tagNm +
        ' X ' +
        (this.grpFlter.subGrp && this.grpFlter.subGrp.labId ? this.grpFlter.subGrp.tagNm : '数值')
      const tips2 =
        (this.grpFlter.subGrp && this.grpFlter.subGrp.labId ? this.grpFlter.subGrp.tagNm : '数值') +
        ' X ' +
        this.grpFlter.mainGrp.tagNm
      return this.grpFlter.mainGrp.graphType === 'bar' ? tips1 : tips2
    }
  },
  methods: {
    setLoading(type = 'default') {
      if (type === 'default') this.loading = true
      this.compare.loading = true
    },
    refreshChart(data = {}) {
      this.wrong = !!data.wrong
      this.list = data.labGrps || []
      this.showList = data.labGrps && data.labGrps.length > 0
      if (this.showList) {
        this.$nextTick(() => {
          if (!this.barChart)
            this.barChart = echarts.init(
              document.getElementById(`factory-profile-${this.grpFlter.mainGrp.labId}-#${this.grpFlter.index}`)
            )
          const _this = this
          let xAxis = []
          let yAxis = []
          let rotate = 0
          let series = []
          let legend = []
          let subText = []
          let seriesParam = {}
          let isDimen = false
          if (data.subLabId) {
            // 堆叠图
            isDimen = true
            data.labGrps.forEach(item => {
              let label = item.desc || item.code
              let subLabel = item.subDesc
              if (
                this.grpFlter.mainGrp.valueType == '6' ||
                this.grpFlter.mainGrp.valueType == '7' ||
                this.grpFlter.subGrp.valueType == '6' ||
                this.grpFlter.subGrp.valueType == '7'
              ) {
                label = label.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')
                subLabel = subLabel.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')
              }
              if (!xAxis.includes(label)) xAxis.push(label)
              if (!seriesParam[subLabel]) {
                seriesParam[subLabel] = {
                  [label]: item.value
                }
              } else {
                seriesParam[subLabel][label] = item.value
              }
              if (!legend.includes(subLabel)) legend.push(subLabel)
              if (label && label.length >= 5) rotate = 40
            })
            Object.keys(seriesParam).forEach((item, sindex) => {
              let xData = []
              let color = ''
              if (sindex <= this.colorList.length) color = this.colorList[sindex]
              else {
                let r = Math.floor(Math.random() * 256)
                let g = Math.floor(Math.random() * 256)
                let b = Math.floor(Math.random() * 256)
                color = 'rgb(' + r + ',' + g + ',' + b + ')'
              }
              xAxis.forEach(xLabel => {
                xData.push(seriesParam[item][xLabel] ? seriesParam[item][xLabel] : 0)
              })
              series.push({
                name: item,
                type: 'bar',
                color: color,
                barWidth:
                  (this.grpFlter.mainGrp.graphType === 'stack' && xAxis.length >= 5) || xAxis.length > 10 ? null : 30,
                stack: 'profile',
                data: xData
              })
            })
          } else {
            if (data.groupTyp === 'enum') {
              data.labGrps.forEach(item => {
                let label = item.desc || item.code
                xAxis.push(label)
                yAxis.push(item.value)
                if (item.desc && item.desc.length >= 5) rotate = 40
              })
            } else {
              Object.values(this.grpFlter.mainGrp.rangeInfo).forEach(item => {
                let label = item
                const target = data.labGrps.find(grp => grp.desc === label)
                if (Number(this.grpFlter.mainGrp.valueType) === 6 || Number(this.grpFlter.mainGrp.valueType) === 7) {
                  label = label.replace(/-/g, ' -∞')
                  label = label.replace(/[+]/g, ' +∞')
                  // legend.forEach((item, index) => (legend[index] = item.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')))
                }
                xAxis.push(label)
                yAxis.push(target ? target.value : 0)
                if (label && label.length >= 8) rotate = 40
              })
              if (data.numLabGrps) {
                data.numLabGrps.forEach(numLab => {
                  subText.push(`{a|${numLab.funcName}} ${numLab.funcResult}`)
                })
              }
            }
            series = [
              {
                type: 'bar',
                barWidth:
                  (this.grpFlter.mainGrp.graphType === 'stack' && xAxis.length >= 5) || yAxis.length > 10 ? null : 30,
                data: yAxis,
                itemStyle: {
                  color: '#0f80ff'
                },
                label: {
                  normal: {
                    show: true,
                    position: this.grpFlter.mainGrp.graphType === 'stack' ? 'right' : 'top',
                    color: '#666',
                    rotate: this.grpFlter.mainGrp.graphType === 'bar' && yAxis.length > 15 ? 90 : 0,
                    align:
                      this.grpFlter.mainGrp.graphType === 'stack' ||
                      (this.grpFlter.mainGrp.graphType === 'bar' && yAxis.length > 15)
                        ? 'top'
                        : 'middle',
                    verticalAlign: 'middle',
                    formatter: function(params) {
                      return ((params.value / _this.grpTotal.grpTotal) * 100).toFixed(2) + '%'
                    }
                  }
                }
              }
            ]
          }
          let axisParams1 = [
            {
              type: 'category',
              axisLabel: {
                show: true,
                color: '#666',
                rotate: this.grpFlter.mainGrp.graphType === 'stack' ? 0 : rotate,
                interval: 0,
                formatter: function(params) {
                  let label = params
                  if (params.length >= 20) {
                    label = params.split('~')[0] + '~ \n ' + params.split('~')[1]
                  }
                  return label
                }
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#666'
                }
              },
              axisTick: {
                show: false
              },
              data: xAxis
            }
          ]
          let axisParams2 = {
            type: 'value',
            axisLabel: {
              color: '#666'
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#666'
              }
            },
            axisTick: {
              show: true,
              inside: true,
              lineStyle: {
                color: '#eee'
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#eee'
              }
            }
          }
          let option = {
            title: [
              {
                text: this.grpFlter.mainGrp.groupName,
                textStyle: {
                  fontSize: 16,
                  fontWeight: 700
                },
                subtext: subText.join(' '),
                subtextStyle: {
                  color: '#63708a',
                  rich: {
                    a: {
                      padding: [5, 10],
                      lineHeight: 10,
                      color: '#63708a',
                      backgroundColor: '#f2f6ff',
                      borderRadius: 2
                    }
                  }
                }
              },
              {
                text: this.axisTips,
                top: 1,
                left: this.grpFlter.mainGrp.groupName.length * 15 + 20,
                textStyle: {
                  fontSize: 13,
                  fontWeight: 700,
                  color: '#999'
                }
              }
            ],
            tooltip: isDimen
              ? {
                  trigger: 'axis',
                  axisPointer: 'shadow',
                  confine: true
                }
              : {
                  trigger: 'axis',
                  confine: true,
                  formatter: function(params) {
                    return (
                      params[0].name +
                      '<br/>数值：' +
                      params[0].value +
                      '<br/>占比：' +
                      ((params[0].value / _this.grpTotal.grpTotal) * 100).toFixed(2) +
                      '%'
                    )
                  }
                },
            legend: {
              show: isDimen,
              type: 'scroll',
              top: 25,
              right: 5,
              data: legend
            },
            grid: {
              top: '60',
              left: 0,
              right: '50',
              bottom: 0,
              containLabel: true
            },
            xAxis: this.grpFlter.mainGrp.graphType === 'stack' ? axisParams2 : axisParams1,
            yAxis: this.grpFlter.mainGrp.graphType === 'stack' ? axisParams1 : axisParams2,
            series: series
          }
          this.barChart.setOption(option, true)
          window.addEventListener('resize', () => {
            this.barChart.resize()
          })
        })
      } else {
        if (this.barChart) {
          this.barChart.dispose()
          this.barChart = null
        }
      }
      this.loading = false
    },
    refreshCompareChart(data = {}) {
      this.compare.wrong = !!data.wrong
      this.compare.list = data.labGrps || []
      let showList = data.labGrps && data.labGrps.length > 0
      if (this.compare.list.length) {
        let flag = false
        this.compare.list.forEach(item => {
          if (item.value > 0) flag = true
        })
        showList = flag
      }
      this.compare.showList = showList
      if (showList) {
        this.$nextTick(() => {
          this.compare.barChart = echarts.init(
            document.getElementById(`factory-profile-compare-${this.grpFlter.mainGrp.labId}-#${this.grpFlter.index}`)
          )
          const _this = this
          let xAxis = []
          let yAxis = []
          let rotate = 0
          let series = []
          let legend = []
          let subText = []
          let seriesParam = {}
          let isDimen = false
          if (data.subLabId) {
            // 堆叠图
            isDimen = true
            data.labGrps.forEach(item => {
              let label = item.desc || item.code
              let subLabel = item.subDesc
              if (
                this.grpFlter.mainGrp.valueType == '6' ||
                this.grpFlter.mainGrp.valueType == '7' ||
                this.grpFlter.subGrp.valueType == '6' ||
                this.grpFlter.subGrp.valueType == '7'
              ) {
                label = label.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')
                subLabel = subLabel.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')
              }
              if (!xAxis.includes(label)) xAxis.push(label)
              if (!seriesParam[subLabel]) {
                seriesParam[subLabel] = {
                  [label]: item.value
                }
              } else {
                seriesParam[subLabel][label] = item.value
              }
              if (!legend.includes(subLabel)) legend.push(subLabel)
              if (label && label.length >= 5) rotate = 40
            })
            Object.keys(seriesParam).forEach((item, sindex) => {
              let xData = []
              let color = ''
              if (sindex <= this.colorList.length) color = this.colorList[sindex]
              else {
                let r = Math.floor(Math.random() * 256)
                let g = Math.floor(Math.random() * 256)
                let b = Math.floor(Math.random() * 256)
                color = 'rgb(' + r + ',' + g + ',' + b + ')'
              }
              xAxis.forEach(xLabel => {
                xData.push(seriesParam[item][xLabel] ? seriesParam[item][xLabel] : 0)
              })
              series.push({
                name: item,
                type: 'bar',
                color: color,
                barWidth:
                  (this.grpFlter.mainGrp.graphType === 'stack' && xAxis.length >= 5) || xAxis.length > 10 ? null : 30,
                stack: 'profile',
                data: xData
              })
            })
          } else {
            if (data.groupTyp === 'enum') {
              data.labGrps.forEach(item => {
                let label = item.desc || item.code
                xAxis.push(label)
                yAxis.push(item.value)
                if (item.desc && item.desc.length >= 5) rotate = 40
              })
            } else {
              Object.values(this.grpFlter.mainGrp.rangeInfo).forEach(item => {
                let label = item
                const target = data.labGrps.find(grp => grp.desc === label)
                if (Number(this.grpFlter.mainGrp.valueType) === 6 || Number(this.grpFlter.mainGrp.valueType) === 7) {
                  label = label.replace(/-/g, ' -∞')
                  label = label.replace(/[+]/g, ' +∞')
                  legend.forEach((item, index) => (legend[index] = item.replace(/-/g, ' -∞').replace(/[+]/g, ' +∞')))
                }
                xAxis.push(label)
                yAxis.push(target ? target.value : 0)
                if (label && label.length >= 8) rotate = 40
              })
              if (data.numLabGrps) {
                data.numLabGrps.forEach(numLab => {
                  subText.push(`{a|${numLab.funcName}} ${numLab.funcResult}`)
                })
              }
            }
            series = [
              {
                type: 'bar',
                barWidth:
                  (this.grpFlter.mainGrp.graphType === 'stack' && xAxis.length >= 5) || yAxis.length > 10 ? null : 30,
                data: yAxis,
                itemStyle: {
                  color: '#0f80ff'
                },
                label: {
                  normal: {
                    show: true,
                    position: this.grpFlter.mainGrp.graphType === 'stack' ? 'right' : 'top',
                    color: '#666',
                    rotate: this.grpFlter.mainGrp.graphType === 'bar' && yAxis.length > 15 ? 90 : 0,
                    align:
                      this.grpFlter.mainGrp.graphType === 'stack' ||
                      (this.grpFlter.mainGrp.graphType === 'bar' && yAxis.length > 15)
                        ? 'top'
                        : 'middle',
                    verticalAlign: 'middle',
                    formatter: function(params) {
                      return ((params.value / _this.grpTotal.compareTotal) * 100).toFixed(2) + '%\n'
                    }
                  }
                }
              }
            ]
          }
          let axisParams1 = [
            {
              type: 'category',
              axisLabel: {
                show: true,
                color: '#666',
                rotate: this.grpFlter.mainGrp.graphType === 'stack' ? 0 : rotate,
                interval: 0,
                formatter: function(params) {
                  let label = params
                  if (params.length >= 20) {
                    label = params.split('~')[0] + '~ \n ' + params.split('~')[1]
                  }
                  return label
                }
              },
              axisLine: {
                show: true,
                lineStyle: {
                  color: '#666'
                }
              },
              axisTick: {
                show: false
              },
              data: xAxis
            }
          ]
          let axisParams2 = {
            type: 'value',
            axisLabel: {
              color: '#666'
            },
            axisLine: {
              show: true,
              lineStyle: {
                color: '#666'
              }
            },
            axisTick: {
              show: true,
              inside: true,
              lineStyle: {
                color: '#eee'
              }
            },
            splitLine: {
              show: true,
              lineStyle: {
                color: '#eee'
              }
            }
          }
          // data.labGrps.forEach(item => {
          //   xAxis.push(item.desc || item.code)
          //   yAxis.push(item.value)
          //   count += item.value
          //   if (item.desc && item.desc.length >= 5) rotate = 40
          // })
          let option = {
            title: [
              {
                text: this.grpFlter.mainGrp.groupName,
                textStyle: {
                  fontSize: 16,
                  fontWeight: 700
                },
                subtext: subText.join(' '),
                subtextStyle: {
                  color: '#63708a',
                  rich: {
                    a: {
                      padding: [5, 10],
                      lineHeight: 10,
                      color: '#63708a',
                      backgroundColor: '#f2f6ff',
                      borderRadius: 2
                    }
                  }
                }
              },
              {
                text: this.axisTips,
                top: 1,
                left: this.grpFlter.mainGrp.groupName.length * 15 + 20,
                textStyle: {
                  fontSize: 14,
                  fontWeight: 700,
                  color: '#999'
                }
              }
            ],
            tooltip: isDimen
              ? {
                  trigger: 'axis',
                  axisPointer: 'shadow',
                  confine: true
                }
              : {
                  trigger: 'axis',
                  confine: true,
                  formatter: function(params) {
                    return (
                      params[0].name +
                      '<br/>数值：' +
                      params[0].value +
                      '<br/>占比：' +
                      ((params[0].value / _this.grpTotal.compareTotal) * 100).toFixed(2) +
                      '%'
                    )
                  }
                },
            legend: {
              show: isDimen,
              type: 'scroll',
              top: 18,
              right: 5,
              data: legend
            },
            grid: {
              top: '60',
              left: 0,
              right: '50',
              bottom: 0,
              containLabel: true
            },
            xAxis: this.grpFlter.mainGrp.graphType === 'stack' ? axisParams2 : axisParams1,
            yAxis: this.grpFlter.mainGrp.graphType === 'stack' ? axisParams1 : axisParams2,
            series: series
          }
          this.compare.barChart.setOption(option, true)
          window.addEventListener('resize', () => {
            this.compare.barChart.resize()
          })
        })
      } else {
        if (this.compare.barChart) {
          this.compare.barChart.dispose()
          this.compare.barChart = null
        }
      }
      this.compare.loading = false
    }
  }
}
</script>

<style lang="scss">
@import './chart.scss';
</style>
